<template>
    <div class="content-box">
      <div ref="searchBox" class="search-box flex" v-show="showSearch">
        <el-form
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          label-width="100px"
        >
          <el-form-item label="省市名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入"
              clearable
              style="width: 240px; margin-right: 20px"
            ></el-input>
          </el-form-item>
          <el-form-item label="省市" prop="code">
            <el-cascader
                ref="cascaderQueryRef"
                filterable
                v-model="queryParams.code"
                v-removeAriaHidden
                @change="cascaderQueryChangeFun"
                :options="areaList"
                :props="{
                  value: 'code',
                  label: 'name',
                  children: 'list',
                  // 在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组
                  emitPath: false,
                  // 是否严格的遵守父子节点不互相关联
                  checkStrictly: true,
                }"
                clearable
                placeholder="请选择省市"
                style="width: 240px; margin-right: 20px"
              ></el-cascader>
          </el-form-item>
          <el-form-item label="评分类型" prop="scoreType">
            <el-select
              v-model="queryParams.scoreType"
              clearable
              filterable
              placeholder="请选择"
              style="width: 240px; margin-right: 20px"
            >
              <el-option
                v-for="(item, index) in scoreTypeOption"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              plain
              >查询</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
            <el-button
              type="primary"
              size="mini"
              v-hasPermi="['globalConfig:pickCity:add']"
              @click="handelDialog('添加', null)"
              >添加省市评分</el-button
            >
          </el-form-item>
        </el-form>
      </div>
  
      <div class="table-box">
        <el-row :gutter="10" class="mb8">
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="handleQuery"
            :columns="columns"
          ></right-toolbar>
        </el-row>
        <el-table
          v-sticky-header
          ref="table"
          v-loading="loading"
          :data="dataList"
        >
          <template v-for="(item,index) in columns.slice(0, columns.length - 1)">
            <el-table-column
              :key="index"
              :label="item.label"
              :prop="item.prop"
              :width="getColumnWidth(index)"
              align="center"
              :fixed="item.fixed"
              :sortable="item.sortable ? item.sortable : false"
              :show-overflow-tooltip="item.showTooltip"
              v-if="item.visible"
            >
            </el-table-column>
          </template>
          <el-table-column
            fixed="right"
            :prop="columns[columns.length - 1].prop"
            :label="columns[columns.length - 1].label"
            align="center"
            :width="getColumnWidth(columns.length - 1)"
            v-if="columns[columns.length - 1].visible"
          >
            <template slot-scope="scope">
              <div :class="['flex-center',device === 'mobile'?'flex':'']">
                <el-button
                  type="text"
                  v-hasPermi="['globalConfig:pickCity:query']"
                  :style="{marginLeft: device === 'mobile'?'10px':'0px'}"
                  @click="handelDialog('查看', scope.row)"
                  >查看</el-button
                 >
                <el-button
                  type="text"
                  v-hasPermi="['globalConfig:pickCity:edit']"
                  @click="handelDialog('编辑', scope.row)"
                  >编辑</el-button
                >
                <el-popconfirm
                  title="确定要删除该省市评分吗？"
                  style="margin-left: 10px"
                  @cancel="hanCancelDel"
                  @confirm="handelDel(scope.row)"
                  v-hasPermi="['globalConfig:pickCity:remove']"
                >
                  <el-button
                    slot="reference"
                    type="text"
                    ><span style="color: #ff116e">删除</span></el-button
                  >
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 使用分页插件 -->
        <pagination
          v-show="total > 0"
          :total="total"
          :page-sizes="[10, 50, 100, 200, 500]"
          :page.sync="queryParams.pageIndex"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
      <!-- 新增/编辑/查看 对话框 -->
      <el-dialog
        :title="title"
        width="800px"
        :visible.sync="dialogShow"
        :before-close="handleClose"
      >
        <el-form :model="form" :rules="rules" label-width="140px" ref="formRef">
          <el-form-item label="评分类型" prop="scoreType">
            <el-select
              v-model="form.scoreType"
              clearable
              filterable
              placeholder="请选择"
              style="width: 100%"
              :disabled="viewsOptionState"
              @change="scoreTypeChange"
            >
              <el-option
                v-for="(item, index) in scoreTypeOption"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="省市" prop="code">
            <el-cascader
                ref="cascaderFormRef"
                filterable
                v-model="form.code"
                v-removeAriaHidden
                @change="cascaderFormChangeFun"
                :options="proviceOrCityList"
                :props="{
                  value: 'code',
                  label: 'name',
                  children: 'list',
                  disabled: true,
                  // 在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组
                  emitPath: false,
                  // 是否严格的遵守父子节点不互相关联
                  checkStrictly:form.scoreType==2?false:true,
                }"
                clearable
                :disabled="viewsOptionState"
                placeholder="请选择省市"
                style="width: 100%"
              ></el-cascader>
          </el-form-item>
          <el-form-item label="省市评分" prop="scoreNum">
              <el-input-number 
                v-model="form.scoreNum" 
                controls-position="right" 
                placeholder="请输入"
                :min="0" 
                style="width: 100%;"
                :disabled="viewsOptionState"
              >
              </el-input-number>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" v-if="!viewsOptionState">
          <el-button type="primary" @click="handleSubmit('formRef')"
            >确 定</el-button
          >
          <el-button @click="handleClose">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import tableStickyMixins from "@/mixins/tableStickyMixins";
  import { mapGetters } from "vuex";
  import {
    addOrEdit,
    deleteById,
    queryCityConfigByPage,
  } from "@/api/globalConfig/pickCity";
  import {
    addOrEditCityConfig,
    deleteCityConfigById,
    queryupPickCityConfigByPage,

  } from "@/api/business/upPickManagement"
  
  import { getAreaCodeTreeList } from "@/api/system/areaCode";
  
  export default {
    // 定义名字用于标识该组件是否被keep-alive缓存
    name: "PickCity",
    data() {
      return {
        // 数据列表
        dataList: [],
        // 总条数
        total: 0,
        // 查询参数
        queryParams: {
          pageIndex: 1,
          pageSize: 10,
        },
        loading: false,
        // 显示搜索栏
        showSearch: true,
        // 弹框标题
        title: "",
        // 弹框显示状态
        dialogShow: false,
        // 弹框的表单信息
        form: {
          // 默认状态启用
          status:1
        },
        // 弹框表单校验规则
        rules: {
        },
        // 评分类型筛选项
        scoreTypeOption: [
          { label: "省", value: 1 },
          { label: "市", value: 2 },
        ],
        // 全国省市区列表(树型结构)
        areaList: [],
        // 全国省市区对象形式
        areaObj:{},
        // 路由参数对象
        query:{
        },

      };
    },
    mixins: [tableStickyMixins],
    watch: {
      columns: {
        handler() {
          this.updateTableHeight();
        },
        deep: true,
      },
    },
    created() {
      this.init();
    },
    computed: {
      ...mapGetters(["sidebar", "device"]),
      // 计算当前列元素在所处环境的宽度
      getColumnWidth() {
        return (index) => {
          return this.isMobile
            ? this.columns[index].mobileWidth
            : this?.sidebar?.opened
            ? this.columns[index].pcWidth - this.slightWidth
            : this.columns[index].pcWidth + 17;
        };
      },
  
      // (是否处于查看操作禁用表单项)
      viewsOptionState() {
        return this.title === "查看省市评分";
      },
      // 表格列信息计算属性
      columns(){
        return [
          {label: `ID`,prop: "id",visible: true,pcWidth: 170,mobileWidth: 100,fixed: this.device === 'mobile'? null: 'left',showTooltip: true,},
          {label: `上游公司名称`,prop: "companyName",visible: true,pcWidth: 200,mobileWidth: 110,fixed:this.device === 'mobile'? null: 'left',showTooltip: true,},
          {label: `产品简称`,prop: "simpleName",visible: true,pcWidth: 200,mobileWidth: 100,fixed: this.device === 'mobile'? null: 'left',showTooltip: true,},
          {label: `产品名称`,prop: "productName",visible: true,pcWidth: 200,mobileWidth: 100,fixed: this.device === 'mobile'? null: 'left',showTooltip: true,},
          {label: `评分类型`,prop: "scoreTypeStr",visible: true,pcWidth: 170,mobileWidth: 110,fixed: null,showTooltip: true,},
          {label: `省市名称`,prop: "name",visible: true,pcWidth: 200,mobileWidth: 110,fixed: null,showTooltip: true,sortable: true,},
          {label: `省市编码`,prop: "code",visible: true,pcWidth: 170,mobileWidth: 110,fixed: null,showTooltip: true,sortable: true,},
          {label: `省市评分`,prop: "scoreNum",visible: true,pcWidth: 170,mobileWidth: 110,fixed: null,showTooltip: false,sortable: true,},
          {label: `操作`,prop: "operation",visible: true,pcWidth: 130,mobileWidth: 80,fixed: "right",showTooltip: true,},
        ]
      },
      // 省市列表计算属性
      proviceOrCityList(){
        if(this?.areaList && this?.areaList?.length){
          if(this.form?.scoreType != 2 ){
            return this.areaList.map(item => ({...item,list:null}))
          }
          // 对北京市和天津市单独处理
          return this?.areaList.map(pre=>{
            if(pre?.name == '北京市' || pre?.name == '天津市'){
              return {...pre,code:'provice'+pre?.code}
            }
            return pre
          })
        }else{
          return []
        }
      }
    },
    methods: {
      // 级联筛选器改变事件
      cascaderQueryChangeFun(){
        const cascader = this.$refs.cascaderQueryRef;
        if (cascader) {
          if (cascader.handleClear) {
            cascader.handleClear(); // 清除 UI 上的输入和选中
          }
          // if (cascader.handleExpandChange) {
          //   cascader.handleExpandChange([]); // 重置展开路径，回到根节点
          // }
        }
        // 强制更新组件
        this.$forceUpdate();
      },
      // 级联筛选器改变事件
      cascaderFormChangeFun(){
        const cascader = this.$refs.cascaderFormRef;
        if (cascader) {
          if (cascader.handleClear) {
            cascader.handleClear(); // 清除 UI 上的输入和选中
          }
          // if (cascader.handleExpandChange) {
          //   cascader.handleExpandChange([]); // 重置展开路径，回到根节点
          // }
        }
        // 强制更新组件
        this.$forceUpdate();
      },
      scoreTypeChange(){
         //重置code 
         this.$set(this.form,'code',undefined)
      },
      // 获取全国省市区列表
      getProvinceCityList() {
        getAreaCodeTreeList().then((res) => {
          this.areaList = res?.data;
          this.areaObj = this.flattenAreaObj(res?.data);
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.$set(this.queryParams, "pageIndex", 1);
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        // 完全重置到初始状态
        this.$set(this, "queryParams", {
          pageIndex: 1,
          pageSize: 10,
        });
        this.init();
      },
      init() {
        if(this.$route?.query?.upProductId){
           this.query = this.$route.query
        }
        this.getList();
        this.getProvinceCityList();
      },
      /** 查询列表 */
      getList() {
        this.loading = true;
        // 设置采量传过来的id
        if(this.query.upProductId){
              this.$set(this.queryParams,'upProductId',this.query.upProductId);
        }
        [this.query.upProductId?queryupPickCityConfigByPage:queryCityConfigByPage][0](this.queryParams).then((response) => {
          // 解决id为number类型精度丢失问题
          this.dataList = response?.data?.list.map((row) => {
            return {
              ...row,
              id: row.id.toString(),
            };
          });
          this.total = response?.data?.total;
          this.loading = false;
        }).catch((err) => {
          setTimeout(() => {// 延迟2s后自动取消加载状态
            this.loading = false;
          }, 2000);
        })
      },
      // 获取省市评分详情
      getPickCityDetail(row) {
        this.form = Object.assign({},row);
      },
  
      // 修改表格高度触发回调
      updateTableHeight() {
        this.$nextTick(() => {
          this.$refs.table.doLayout();
        });
      },
      // 处理对话框
      handelDialog(title, row = null) {
        this.title = title + "省市评分";
        switch (title) {
          case "查看":
            // 获取省市评分详细信息回显数据
            this.getPickCityDetail(row);
            break;
          case "添加":
            break;
          case "编辑":
            // 获取省市评分详细信息回显数据
            this.getPickCityDetail(row);
            break;
          default:
          // 其他操作
        }
        this.dialogShow = true;
      },
      /*关闭弹窗*/
      handleClose() {
        this.$refs["formRef"].resetFields();
        this.form = this.$options.data().form;
        this.dialogShow = false;
      },
      // 取消删除
      hanCancelDel() {
        this.$message({
          type: "info",
          message: "已取消删除操作",
        });
      },
      // 删除列表项
      handelDel(row) {
        [this.query.upProductId?deleteCityConfigById:deleteById][0](row?.id).then((res) => {
          if (res.code === 200) {
            this.$message.success("删除成功");
            this.getList();
          }
        });
      },
      // 刷新数据且关闭弹框
      handleRefresh() {
        // 刷新数据
        this.getList();
        // 关闭弹窗
        this.handleClose();
      },
      // 扁平化全国省市地址为对象形式
      flattenAreaObj(data) {
        return data.reduce((obj,pre)=>{
          // 如果存在子节点
          if(pre?.list){
            obj[pre.code] = pre.name
            obj =Object.assign({},obj,this.flattenAreaObj(pre.list))
          }else{
            obj = {...obj,...{[pre.code]:pre.name}}
          }
          return obj
        },{})
      },
      /*提交操作*/
      handleSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let params = {};
            params = JSON.parse(JSON.stringify(this.form));
            console.log(params);
  
            // 省市名字单独处理
            if (this.form?.code) {
              params.name = this.areaObj[params.code];
            }
            // 设置采量传过来的id
            if(this.query.upProductId){
              params.upProductId=this.query.upProductId
            }
            // 判断当前所处操作
            switch (this.title) {
              case "添加省市评分":
                // 添加操作
                console.log("添加", params);
                [this.query.upProductId?addOrEditCityConfig:addOrEdit][0](params).then((res) => {
                  if (res.code === 200) {
                    this.$message.success("添加成功");
                    this.handleRefresh();
                  }
                });
                break;
              case "编辑省市评分":
                // 编辑操作
                console.log("编辑", params);
                [this.query.upProductId?addOrEditCityConfig:addOrEdit][0](params).then((res) => {
                  if (res.code === 200) {
                    this.$message.success("编辑成功");
                    this.handleRefresh();
                  }
                });
                break;
              default:
              // 其他操作
            }
          }
        });
      },
    },
  };
  </script>
  
  <style scoped lang="scss">
  .title {
    font-size: 20px;
    color: #333333;
    font-weight: 500;
  }
  .search-box {
    margin: 0 0 20px;
    padding: 20px 20px 0;
    background: #fff;
    align-items: flex-start;
    border-radius: 6px;
  }
  .search-area {
    position: absolute;
    right: 20px;
  }
  .el-form-item__content {
    flex: 1;
    line-height: 40px;
    position: relative;
    font-size: 14px;
    min-width: 0;
  }
  ::v-deep .el-dialog__body {
    border-top: 1px solid #dfe6ec;
    border-bottom: 1px solid #dfe6ec;
  }
  .el-table {
    // 滚动条加粗
    --scrollbar-height: 9px;
  }
  </style>
  